package com.wis.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@Component
public class UploadPictureUtil {
//    @Value("${upload.upload-dir-windows}")
    private String windowsFilepathPre="D:\\zzz\\v1";

//    @Value("${upload.upload-dir-linux}")
    private String linuxFilepathPre="/home/zzz/v1";

    @Value("${upload.upload-choose}")
    private int choose;

    @Value("${server.port}")
    private String port;


    /**
     * @param file 接受一个文件类型
     * @return
     */
    public String upload(MultipartFile file) {
        //后缀
        String suffix = "";

        try {
            //获取图片名字
            String originalName = file.getOriginalFilename();
            //截取 .xxx
            suffix = originalName.substring(originalName.lastIndexOf(".") + 1);
            //随机码
            String uuid = UUID.randomUUID() + "";

            String filepath;
            if (choose == 1) {
                filepath = windowsFilepathPre + "\\images" + "\\" + uuid + "." +
                        suffix;
            } else {
                filepath = linuxFilepathPre + "/images/" + uuid + "." + suffix;
            }

            //写入文件  填路径
            File files = new File(filepath);
            if (!files.getParentFile().exists()) {
                files.getParentFile().mkdirs(); //创建文件夹
            }
            file.transferTo(files);

            return "/images/" + uuid + "." + suffix;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 删除原先的图片方法
     *
     * @param url
     */
    public void deletePicture(String url) {
        if (choose == 1) {
            url = url.replaceAll("/", "\\\\");
            url = windowsFilepathPre + url;
        } else {
            url = linuxFilepathPre + url;
        }
        File file = new File(url);
        boolean delete = file.delete();
        log.info("图片 " + delete);
    }
}
